<script setup lang="ts">
import { libraryRequestParams, RequestParams } from "@/api/library/type";
//import SingleUpload from "@/components/Upload/SingleUpload.vue";
import {
  libraryList,
  addLibrary,
  delLibrary,
  FormLibrary,
  LibraryOptions,
  updateLibrary,
  uploadFileApi,
} from "@/api/library/index";
import { Picture as IconPicture } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { nextTick, onMounted, reactive, ref, watch } from "vue";
import useUserStore from "@/store/modules/user";
let useStore = useUserStore();
import type {
  ElUpload,
  //UploadProps,
  UploadRawFile,
  UploadRequestOptions,
  //UploadUserFile,
} from "element-plus";

// ================================================================================
// ref
const queryFormRef = ref(); //搜索
const ruleFormRef = ref(); //弹框表单

const ids = ref([] as number[]); //表格全选
const total = ref();
const loading = ref(false);
const dialogVisible = ref(false);
const title = ref("新增");
let LibOptions = ref([] as any);
const ruleForm = ref({ fileUrl: "", filePath: "" } as any);
let queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  libraryName: "",
} as any);
const tableList = ref([{}] as libraryRequestParams[]);
// 自定义校验函数
const validateLibraryName = (rule, value, callback) => {
  const regex = /^[^\d\s!"#$%&'()*+,-./:;<=>?@[\\\]^_`{|}~]+$/;
  if (!regex.test(value)) {
    callback(new Error("图书馆名称不能包含特殊标点字符和数字"));
  } else {
    callback();
  }
};
const rules = reactive({
  // libraryEmail: [
  //   {
  //     required: true,
  //     pattern: /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/,
  //     message: "请输入正确的邮箱地址",
  //     trigger: "blur",
  //   },
  // ],
  libraryName: [
    { required: true, message: "图书馆不能为空", trigger: "blur" },
    { min: 4, max: 15, message: "图书馆名称不能少于4位", trigger: "blur" },
    { validator: validateLibraryName, trigger: "blur" },
  ],
  // libraryBeginTime: [
  //   { required: true, message: "开馆时间不能为空", trigger: "blur" },
  //   // { min: 1, max: 8, message: "请输入正确的开馆时间", trigger: "blur" },
  // ],
  // libraryEndTime: [
  //   { required: true, message: "开馆时间不能为空", trigger: "blur" },
  //   // { min: 1, max: 8, message: "请输入正确的闭馆时间", trigger: "blur" },
  // ],
  // libraryAddress: [
  //   { required: true, message: "图书馆地址不能为空", trigger: "blur" },
  //   // { min: 1, max: 50, message: "图书馆地址过长", trigger: "blur" },
  // ],
  // libraryFullAddress: [
  //   { required: true, message: "图书馆地址不能为空", trigger: "blur" },
  // ],
  // fileUrl: [
  //   {
  //     required: true,
  //     message: "请选择营业执照",
  //     trigger: "change",
  //   },
  // ],
});

// 挂载
onMounted(() => {
  handleQuery();
});
// ================================================================================
/**
 * 枚举
 */
// const getStatusText = (status: any) => {
//   const STATUSES = [
//     { id: "0", name: "预约中" },
//     { id: "1", name: "完成" },
//   ];
//   const matched = STATUSES.find((item) => item.id === status);
//   return matched ? matched.name : "";
// };
/**
 * 查询
 */
const handleQuery = async () => {
  try {
    loading.value = true;
    const res = await libraryList(queryParams);
    //console.log(res, "res");

    tableList.value = res.data.records;

    total.value = res.data.total;
    loading.value = false;
  } catch (error) {
    // console.error(error);
    loading.value = false; // 将 loading 的值设置为 false，以便停止加载动画
  }
};
/**
 * 重置
 */
const resetQuery = () => {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  queryParams.libraryName = "";
  queryFormRef.value.clearValidate();
  handleQuery();
};
/**
 * 行checkbox change事件
 */
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}
/**
 * 打开弹框
 */
const openDialog = async (id?: number) => {
  dialogVisible.value = true;
  const res = await LibraryOptions(useStore.encryptedData);
  LibOptions.value = res.data;

  if (id) {
    const res = await FormLibrary(id as any);
    ruleForm.value = res.data;
    title.value = "修改图书馆";
    srcList.value.splice(0, srcList.value.length);
    srcList.value.push(ruleForm.value.fileUrl);
  } else {
    title.value = "新增图书馆";
    ruleForm.value = {};
    resetUploadFiles(); // 清空上传文件列表
  }
  dialogVisible.value = true;
};
/**
 * 关闭弹框
 */
const close = () => {
  dialogVisible.value = false;
  ruleFormRef.value.resetFields();
  ruleFormRef.value.clearValidate();
  ruleForm.value = {} as any;
  resetUploadFiles(); // 清空上传文件列表
};
/**
 * 处理表单提交事件
 */
const submit = async () => {
  ruleFormRef.value.validate((valid: any) => {
    if (valid) {
      if (isUploading.value) {
        ElMessage.warning("文件上传中，请稍后再试");
        return;
      }

      const userId = ruleForm.value.id;
      loading.value = true;

      if (userId) {
        updateLibrary(ruleForm.value)
          .then(() => {
            ElMessage.success("修改成功");
            close();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        addLibrary(ruleForm.value)
          .then(() => {
            ElMessage.success("新增成功");
            close();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
};

/**
 * 删除
 */
const dell = (id: any) => {
  const userIds = [id || ids.value].join(",");
  if (!userIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }
  ElMessageBox.confirm("确认删除图书馆?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    // console.log(Number(userIds), userIds);
    delLibrary(id).then((res) => {
      if (res.code == 200) {
        ElMessage.success("删除成功");
        handleQuery();
      }
    });
  });
};
const handleSizeChange = (val: number) => {
  queryParams.pageSize = val;
  queryParams.pageNum = 1;

  handleQuery();
};
const handleCurrentChange = (val: number) => {
  queryParams.pageNum = val;
  handleQuery();
  window.scrollTo({ top: 0, behavior: "smooth" }); // 立即回到顶部，并使用平滑滚动效果
};

/**
 * 限制用户上传文件的格式和大小
 */
const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB
const ALLOWED_TYPES = [
  "image/bmp", // BMP
  "image/jpeg", // JPEG
  "image/png", // PNG
  "image/gif", // GIF
  "image/tiff", // TIFF
  "image/svg+xml", // SVG
  "image/webp", // WebP
];
const fileToUpload = ref<File | null>(null); // 用于存储待上传的文件
function handleBeforeUpload(file: UploadRawFile) {
  const isAllowedType = ALLOWED_TYPES.includes(file.type);
  if (!isAllowedType) {
    ElMessage.warning(
      "只允许上传 BMP、JPEG、PNG、GIF、TIFF、SVG、WebP 格式的图片"
    );
    return false;
  }
  if (file.size > MAX_FILE_SIZE) {
    ElMessage.warning("上传图片不能大于10M");
    return false;
  }
  fileToUpload.value = file; // 存储文件
  return true;
}

/**
 * 自定义图片上传
 *
 * @param options
 */

const srcList = ref<string[]>([]);

const uploadRef = ref<InstanceType<typeof ElUpload>>();
const isUploading = ref(false); // 用于跟踪上传状态
async function uploadFile(options: UploadRequestOptions): Promise<void> {
  //console.log("上传文件触发", options.file); // 调试信息
  try {
    isUploading.value = true; // 开始上传
    const { data: fileInfo } = await uploadFileApi(options.file);
    ruleForm.value.fileUrl = fileInfo.fileUrl;
    ruleForm.value.filePath = fileInfo.filePath;
    srcList.value = [fileInfo.fileUrl];
  } catch (error) {
    console.error("上传失败:", error);
    ElMessage.error("上传失败，请重试");
  } finally {
    isUploading.value = false; // 上传完成
  }
}
// 监听 dialogVisible 变化
watch(dialogVisible, (newVal) => {
  if (newVal) {
    resetUploadFiles();
  }
});

// 重置上传文件
function resetUploadFiles() {
  nextTick(() => {
    if (uploadRef.value) {
      uploadRef.value.clearFiles(); // 清空文件列表
    }
  });
}
const indexMethod = (index: any) => {
  // 1、index:代表当前行数据的下标
  // 2、下标+1:  分页不要纠结：这块不是业务，完全是数学问题！
  return index + 1 + (queryParams.pageNum - 1) * queryParams.pageSize;
};
</script>

<template>
  <div class="app-container">
    <el-dialog
      v-model="dialogVisible"
      :title="title"
      width="600px"
      append-to-body
      @close="close"
    >
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="120px"
        status-icon
      >
        <el-form-item label="图书馆" prop="libraryName">
          <el-input
            style="width: 350px"
            v-model="ruleForm.libraryName"
            placeholder="请输入图书馆名称"
          />
        </el-form-item>
        <el-form-item label="图书馆邮箱" prop="libraryEmail">
          <el-input
            style="width: 350px"
            v-model="ruleForm.libraryEmail"
            placeholder="请输入图书馆邮箱"
          />
        </el-form-item>
        <el-form-item label="图书馆地址" prop="libraryAddress">
          <el-input
            style="width: 350px"
            v-model="ruleForm.libraryAddress"
            placeholder="请输入图书馆地址"
          />
        </el-form-item>
        <el-form-item label="图书馆详细地址" prop="libraryFullAddress">
          <el-input
            style="width: 350px"
            v-model="ruleForm.libraryFullAddress"
            placeholder="请输入图书馆详细地址"
          />
        </el-form-item>
        <el-form-item label="营业执照" prop="fileUrl">
          <el-image
            style="width: 100px; height: 100px"
            :src="ruleForm.fileUrl"
            :zoom-rate="1.2"
            :max-scale="7"
            :min-scale="0.2"
            fit="cover"
            :preview-src-list="srcList"
          >
            <template #error>
              <div class="image-slot">
                <el-icon><icon-picture /></el-icon>
              </div>
            </template>
          </el-image>

          <el-upload
            :show-file-list="false"
            ref="uploadRef"
            class="upload-demo"
            action="#"
            :before-upload="handleBeforeUpload"
            :http-request="uploadFile"
          >
            <el-button type="primary" link>上传文件</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submit" :disabled="isUploading"
            >确 定</el-button
          >
          <el-button @click="close">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <div class="search">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="图书馆" prop="name">
          <el-input
            v-model="queryParams.libraryName"
            placeholder="请输入图书馆名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery" icon="Search"
            >搜索</el-button
          >
          <el-button @click="resetQuery" icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-card>
      <template #header>
        <el-button icon="Plus" type="success" @click="openDialog()"
          >新增</el-button
        >
        <!-- <el-button type="danger" :disabled="ids.length === 0" icon="Delete"
          >删除</el-button
        > -->
      </template>
      <el-table
        v-loading="loading"
        highlight-current-row
        :data="tableList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="index"
          width="80"
          label="序号"
          :align="'center'"
          :index="indexMethod"
        />
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <el-table-column label="图书馆名称" prop="libraryName" align="center" />
        <el-table-column
          label="图书馆地址"
          prop="libraryAddress"
          align="center"
        />
        <el-table-column
          label="详细地址"
          prop="libraryFullAddress"
          align="center"
        />

        <el-table-column fixed="right" label="操作" align="center" width="220">
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              size="small"
              @click="openDialog(row.id)"
              icon="Edit"
              >编辑</el-button
            >
            <el-button
              type="primary"
              link
              size="small"
              @click="dell(row.id)"
              icon="Delete"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="margin-top: 15px"
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 30, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: var(--el-fill-color-light);
  color: var(--el-text-color-secondary);
  font-size: 30px;
}
.image-slot .el-icon {
  font-size: 20px;
}
</style>
